<?php

/**
 * JingYao-backend
 *
 * @link     https://gitee.com/wang-zhihui-release/jingyao-backend
 * @apiDocument https://gitee.com/wang-zhihui-release/jingyao-backend/wikis/
 */

namespace App\Services;

use App\Enums\AdminActionTypeEnum;
use App\Enums\AssessTemplateTypeEnum;
use App\Enums\EnableStatusEnum;
use App\Exceptions\ApiException;
use App\Format\AdminUserAssessLogFormat;
use App\Models\AdminUser;
use App\Models\AdminUserAssessLog;
use App\Models\AssessTemplate;
use Illuminate\Support\Facades\Log;

class AdminUserService
{
    public function assessAdminUser(AdminUserAssessLogFormat $adminUserAssessLogFormat)
    {
        $exist = AssessTemplate::query()
            ->where('id', $adminUserAssessLogFormat->getAssessTemplateId())
            ->where('type', AssessTemplateTypeEnum::ASSESS_ADMIN_USER)
            ->where('status', EnableStatusEnum::ENABLE)
            ->exists();
        if (! $exist) {
            throw new ApiException('模版不存在', 1);
        }
        $adminUserAssessLogFormat->setAssessTime(time());
        adminLog(new AdminUserAssessLog(), AdminActionTypeEnum::CREATE, '考核村委');
        AdminUserAssessLog::query()->create($adminUserAssessLogFormat->toArrayNotNull());
    }

    public function deleteAdminUser(int $adminUserId)
    {
        adminLog(new AdminUser(), AdminActionTypeEnum::DELETE, '删除管理员');
        AdminUser::query()->find($adminUserId)->delete();
    }

    public function getAdminUserAssessLog(int $adminUserId)
    {
        $assessLogs = AdminUserAssessLog::query()
            ->with(['assessTemplate', 'assessTemplateRule', 'assessTemplate.rules'])
            ->where('admin_user_id', $adminUserId)->get();
        return $this->groupUserAdminAccess($assessLogs->toArray());
    }

    private function groupUserAdminAccess(array $userAccessLogs)
    {
        if (empty($userAccessLogs)) {
            return [];
        }
        $res = [];
        $ruleScoreMap = array_column($userAccessLogs, null, 'assess_template_rule_id');
        foreach ($userAccessLogs as $userAccessLog) {
            $assessTemplate = $userAccessLog['assess_template'];
            if (empty($assessTemplate)) {
                Log::error(sprintf('模版 id 【%s】 丢失', $userAccessLog['assess_template_id']));
                return [];
            }
            $assessTemplate['assess_time'] = date('Y-m-d H:i:s', $userAccessLog['assess_time']);
            if (checkArrayExistsInArray($res, $assessTemplate, 'id')) {
                continue;
            }
            $rules = $assessTemplate['rules'];
            foreach ($rules as &$rule) {
                $rule['score'] = $ruleScoreMap[$rule['id']]['score'] ?? 0;
            }
            $assessTemplate['rules'] = $rules;
            array_push($res, $assessTemplate);
        }
        return $res;
    }
}
